package com.lhcai.lc.category.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 56. 合并区间
 *
 * @author liuhuaicai
 * @since 2024-11-17 15:37
 */
public class Lc56 {
    public static void main(String[] args) {
        Lc56 lc56 = new Lc56();
        System.out.println(Arrays.deepToString(lc56.merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}})));
    }

    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[][]{};
        }

        // 排序，start,end从大到小
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] - o2[1];
                } else {
                    return o1[0] - o2[0];
                }
            }
        });
        // 合并数组
        List<int[]> res = new ArrayList<>();
        int count = 0;
        res.add(intervals[0]);
        for (int i = 0; i < intervals.length; i++) {
            int[] a = intervals[i];
            int[] b = res.get(count);
            // 不重叠
            if (a[0] > b[1]) {
                res.add(a);
                count++;
            } else {
                res.remove(count);
                if (a[1] >= b[1]) {
                    b[1] = a[1];
                }
                res.add(b);
            }
        }
        return res.toArray(new int[res.size()][]);
    }
}
